<template>
  <div>
    <a-select
      :placeholder="placeholder"
      :disabled="disabled || !warehouseId"
      :value="value"
      @change="handleChange"
      :mode="multiple ? 'multiple' : 'default'"
      :showSearch="true"
      :filterOption="filterOption"
      :allowClear="true"
      :style="customStyle || {}">
      <a-select-option v-for="item in locationList" :key="item.id" :value="item.id">
        {{ item.locationName }} [{{ item.locationCode }}]
      </a-select-option>
    </a-select>
  </div>
</template>

<script>
  import { getAction } from '@/api/manage'
  import { warehouseLocationListByWarehouseId } from '@/api/wms'

  export default {
    name: 'JSelectWarehouseLocation',
    props: {
      placeholder: {
        type: String,
        default: '请选择库位',
        required: false
      },
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      value: {
        type: String,
        required: false
      },
      warehouseId: {
        type: String,
        required: false
      },
      multiple: {
        type: Boolean,
        default: false,
        required: false
      },
      customStyle: {
        type: Object,
        required: false
      }
    },
    data() {
      return {
        locationList: []
      }
    },
    watch: {
      warehouseId: {
        immediate: true,
        handler(val) {
          if (val) {
            this.loadData(val);
          } else {
            this.locationList = [];
          }
        }
      }
    },
    methods: {
      loadData(warehouseId) {
        if (!warehouseId) return;
        
        warehouseLocationListByWarehouseId({ warehouseId }).then(res => {
          if (res.success) {
            this.locationList = res.result || [];
          }
        });
      },
      handleChange(value) {
        this.$emit('change', value, this.getOptionByValue(value));
        this.$emit('input', value);
      },
      getOptionByValue(value) {
        if (!value || !this.locationList || this.locationList.length === 0) {
          return null;
        }
        
        const selectedLocation = this.locationList.find(item => item.id === value);
        if (selectedLocation) {
          return {
            locationCode: selectedLocation.locationCode,
            locationName: selectedLocation.locationName,
            warehouseId: selectedLocation.warehouseId,
            status: selectedLocation.status
          };
        }
        return null;
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      setLocationList(locationList) {
        this.locationList = locationList;
      }
    }
  }
</script> 